package com.fly.create;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * 
 * @author 00fly
 * @version [版本号, 2011-3-23]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class ConfigUtil
{
    private static ConfigUtil instance = new ConfigUtil();
    
    private Properties config = new Properties();
    
    public static ConfigUtil getInstance()
    {
        return instance;
    }
    
    /*
     * 初始化，仅供内部调用
     */
    public void init()
        throws IOException
    {
        init(new File("default.cfg").getAbsolutePath());
    }
    
    /**
     * @param configPath 配置文件路径，加载指定配置文件用
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public void init(String configPath)
        throws IOException
    {
        InputStream in = null;
        try
        {
            File file = new File(configPath);
            
            // 加载jar外配置文件
            if (file.isAbsolute())
            {
                in = new FileInputStream(file);
            }
            else
            {
                // 加载jar内配置文件
                in = ConfigUtil.class.getClass().getResourceAsStream("/" + configPath);
            }
            config.load(in);
        }
        finally
        {
            if (in != null)
            {
                in.close();
            }
        }
    }
    
    /**
     * 保存配置至fileName
     * 
     * @throws Exception
     */
    public void saveToProperties(String fileName)
        throws Exception
    {
        OutputStream out = null;
        try
        {
            Properties dsProperties = new Properties();
            dsProperties.setProperty("projPath", PatchCreator.projDirTextField.getText());
            dsProperties.setProperty("patchDir", String.valueOf(PatchCreator.patchDirTextField.getText()));
            out = new FileOutputStream(fileName);
            dsProperties.store(out, "PatchCreator Tool Default Config");
        }
        finally
        {
            if (out != null)
            {
                out.close();
            }
        }
    }
    
    public Properties getConfig()
    {
        return config;
    }
}
